package com.pic.mgt.monitor.parser;

import java.io.File;
import java.io.IOException;

import com.pic.mgt.log.IgxLog;
import com.pic.mgt.monitor.RedundantConfirmationFileException;
import com.pic.mgt.monitor.UnitFactory;
import com.pic.mgt.monitor.WrongUnitFormatException;
import com.pic.mgt.monitor.check.UnitFormatChecker;
import com.pic.mgt.unit.Unit;

/*
 * [單元處理]
 * 作用內容:
 * (1) 檢查基本單元檔案名稱格式是否正確(不包含檢查確認檔的內容)
 * (2) 叫用 UnitFactory 建立起 unit
 */
public class SimpleUnitHandler implements UnitHandler {
	private UnitFormatChecker unitFormatChecker;	
	private UnitFactory unitFactory;
	
	@Override
	public Unit parseToUnit(File confirmationFile)
									throws ParseToUnitFormatException,
										   ParseToUnitException, RedundantConfirmationFileException{	
		// ********************** Log **********************
		if (IgxLog.messageLog.isDebugMode()) {
			IgxLog.messageLog.debug(this, "Parsing confirmation file '{}' to unit.",
					confirmationFile.getName());
		}
		// ********************** Log **********************
		
		Unit unit = null;
		
		try {
			// 僅先查檢單元檔案"名稱格式"是否正確(不包含檢查確認檔內容)
			// throws WrongUnitFormatException
			this.unitFormatChecker.check(confirmationFile);
			
			/*
			 *  throws NoMatchHaishinTypeException,
			 *         IOException,
			 *         WrongConfirmationContentFormatException,
			 *         WrongUnitFormatException
			 */			
			unit = this.unitFactory.createUnit(confirmationFile);
		} catch (WrongUnitFormatException e) {
			try {
				throw new ParseToUnitFormatException(
						"SUDA-266 Can't parse confirmation file '" + confirmationFile +
						"' to unit. Due to wrong format.",e);
			} catch (ParseToUnitFormatException e1) {
				// ********************** Log **********************
				IgxLog.messageLog.error(this, e1.getMessage());
				// ********************** Log **********************
				
				throw e1;
			}
		} catch (IOException e) {
			try {
				throw new ParseToUnitException(
						"Can't parse confirmation file '" + confirmationFile +
						"' to unit. Due to I/O error.",e);
			} catch (ParseToUnitException e1) {
				// ********************** Log **********************
				if (IgxLog.messageLog.isDebugMode()) {
					IgxLog.messageLog.debug(this, e1.getMessage());
				}
				// ********************** Log **********************
				
				throw e1;
			}
		}
		
		// ********************** Log **********************
		if (IgxLog.messageLog.isDebugMode()) {
			IgxLog.messageLog.debug(this, "Parsing confirmation file '{}' to unit completed.", confirmationFile.getName());
		}
		// ********************** Log **********************
		
		return unit;
	}
	
	// --- getter and setter ---

	public void setUnitFormatChecker(
			UnitFormatChecker unitFormatChecker) {
		this.unitFormatChecker = unitFormatChecker;
	}

	public void setUnitFactory(UnitFactory unitFactory) {
		this.unitFactory = unitFactory;		
	}
}
